//
//  billViewController.m
//  Park
//
//  Created by 123456 on 2017/11/27.
//  Copyright © 2017年 YTYangK. All rights reserved.
//

#import "billViewController.h"
#import "billTableViewCell.h"
#import "HeadSearchViewAssembly.h"
#import "TimeView.h"
#import "DetailsofthebillViewController.h"
#import "BillViewModel.h"
#import "BillModel.h"
@interface billViewController ()<UITableViewDelegate,UITableViewDataSource,HeadSearchViewAssemblyDelegete>
{
    // 需要其他控件控制刷新
    MJRefreshNormalHeader* header;
    MJRefreshBackNormalFooter* footer;
    int _page;
    BOOL RefreshStatus;//刷新还是加载
    // 搜索头部 Nav
    HeadSearchViewAssembly *titleView;
    // 搜索字符串值
    NSString * searchTextVlue;
    //时间选择器
    TimeView *Tview;
    //记录时间
    int T;
    int T1;
    UIView *view;//遮罩层
    NSString *datestr;//获取时间请求
    int b;//分页
}


@end

@implementation billViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    datestr = @"";
    self.isToSearchUpdate=YES;

    [self Layout];
    
    //注册cell
    [self.BillTableview registerNib:[UINib nibWithNibName:@"billTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.BillTableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];

    //刷新头
    [self refreshTableView];
    //搜索头
    [self setupMiddleNavigationItem];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeplace:) name:@"confirm" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeplace1:) name:@"cancel" object:nil];
    
    

}


- (void)setupMiddleNavigationItem {
    /**  初始化 Nav UI */
    titleView = [[HeadSearchViewAssembly alloc] initWithViewController:self];
    titleView.delegete = self;
    UIBarButtonItem *btn   = [titleView rithtScanBtn];
    self.navigationItem.titleView = titleView;
    self.navigationItem.rightBarButtonItem = btn;
}






- (void)refreshTableView {
    
    header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 0;
        self.isToSearchUpdate = YES;

        [self RequestData:_page];
        RefreshStatus = YES;
    }];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    [header beginRefreshing];
    self.BillTableview.header = header;

        footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.isToSearchUpdate = NO;

            b=_page+19;
            b++;
            _page = b;
            [self RequestData:b];
            RefreshStatus= NO;
        }];
        self.BillTableview.footer = footer;
    
}

-(void)RequestData:(int)page{
   
    
    NSString * str  =  ([searchTextVlue rangeOfString:@"搜索"].location != NSNotFound) ? @"" : searchTextVlue ;
    
    NSDictionary *dic = @{@"token":[NSUD objectForKey:@"token"],@"iDisplayStart":@(page),@"iDisplayLength":@"20",@"findDate":datestr,@"sSearch":str};
    
    NSLog(@"%@",dic);
    
    [BillViewModel requestWithUrlForBill:self andParam:dic success:^(NSMutableArray *model) {
        
        [header endRefreshing];
        [footer endRefreshing];
        
        NSMutableArray *scheduingAry = [BillModel mj_objectArrayWithKeyValuesArray:model];
        
        if (self.isToSearchUpdate) {
            [self.dataArr removeAllObjects];
            
            for (NSDictionary *dic  in scheduingAry) {
                [self.dataArr addObject: dic];
            }

        }else{
            
            for (NSDictionary *dic in scheduingAry) {
                [self.dataArr addObject:dic];
            }
            
        }
        
        [self.BillTableview reloadData];

        
    } failure:^(NSString *error) {
        
        [header endRefreshing];
        [footer endRefreshing];
        [MBProgressHUD showError:error toView:self.view];

    }];
    
    
    
    
    
    
}

#pragma  mark - HeardSearch Delegate
//FIXME: 这里需要重新考虑
- (void)headSearchDeviceForKeyWord:(UITextField *)textView {
    /**
     *  头部搜索
     */
    searchTextVlue = textView.text;
    [header beginRefreshing];
    
    
}





#pragma mark -  TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    return 70;
}


- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    
    billTableViewCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.modelCellData =  self.dataArr[indexPath.row];

    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BillModel *model = self.dataArr[indexPath.row];
    
    DetailsofthebillViewController *d = [[DetailsofthebillViewController alloc]init];
    
    d.idstr = model.id;
    
    [self.navigationController pushViewController:d animated:YES];
    
}


- (IBAction)Date:(UIButton *)sender {
    
    view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT);
    view.backgroundColor = [UIColor clearColor];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;

    [window addSubview:view];
    
    //时间选择器
    Tview = [[NSBundle mainBundle]loadNibNamed:@"TimeView" owner:self options:nil][0];
    Tview.frame = CGRectMake(0,SCREEN_HEIGHT,SCREEN_WIDTH,333);
    [window addSubview:Tview];
    NSDate * date = [NSDate date];//当前时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    
    formatter.dateFormat = @"YYYY";
    formatter1.dateFormat = @"MM";
    NSString *res = [formatter stringFromDate:date];
    T=0;
    for (int i = 2015 ; i<res.intValue; i++) {
        T++;
    }
    
    
    NSString *res1 = [formatter1 stringFromDate:date];
    for (int i = 1 ; i<res1.intValue; i++) {
        T1 = i;
    }
    
    [Tview.TimerPicker selectRow:T inComponent:0 animated:NO];
    [Tview.TimerPicker selectRow:T1 inComponent:1 animated:NO];

    
    
    [UIView animateWithDuration:0.5 animations:^{
        Tview.frame =CGRectMake(0, SCREEN_HEIGHT-333, SCREEN_WIDTH, 333);
        
    }completion:^(BOOL finished) {
        
    }];
}


//通知中心修改月份
- (void)changeplace:(NSNotification *)notification{
    
    [self.DateLabel setTitle:notification.userInfo[@"date"] forState:UIControlStateNormal];
    datestr =notification.userInfo[@"date"];
    
    [view removeFromSuperview];
    [header beginRefreshing];

    
}
- (void)changeplace1:(NSNotification *)notification{

    [view removeFromSuperview];

}

-(void)Layout
{
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"667.0")){
        
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"736.0")){
        

        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
        

    }
    
    
    
}


-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc]init];
    }
    
    return  _dataArr;
}



@end
